package com.exmaple.springcloud.domain;


import com.exmaple.springcloud.enums.ReturnCodeEnum;

import java.io.Serializable;

/**
 * 响应信息主体
 */
public class R<T> implements Serializable
{
    private static final long serialVersionUID = 1L;

    //状态码
    private String code;
    //描述
    private String msg;

    //返回数据
    private T data;

    //接口返回时间戳
    private long timestamp ;

    public static <T> R<T> ok()
    {
        return restResult(null, ReturnCodeEnum.RC200.getCode(), null);
    }

    public static <T> R<T> ok(T data)
    {
        return restResult(data, ReturnCodeEnum.RC200.getCode(), ReturnCodeEnum.RC200.getMessage());
    }

    public static <T> R<T> ok(T data, String msg)
    {
        return restResult(data, ReturnCodeEnum.RC200.getCode(), msg);
    }

    public static <T> R<T> ok( String msg){
        return restResult(null,ReturnCodeEnum.RC200.getCode(), msg);
    }

    public static <T> R<T> fail()
    {
        return restResult(null, ReturnCodeEnum.RC500.getCode(), null);
    }

    public static <T> R<T> fail(String msg)
    {
        return restResult(null, ReturnCodeEnum.RC500.getCode(), msg);
    }

    public static <T> R<T> fail(T data)
    {
        return restResult(data, ReturnCodeEnum.RC500.getCode(), null);
    }

    public static <T> R<T> fail(T data, String msg)
    {
        return restResult(data, ReturnCodeEnum.RC500.getCode(), msg);
    }

    public static <T> R<T> fail(String code, String msg)
    {
        return restResult(null, code, msg);
    }

    private static <T> R<T> restResult(T data, String  code, String msg)
    {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        apiResult.setTimestamp(System.currentTimeMillis());
        return apiResult;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getMsg()
    {
        return msg;
    }

    public void setMsg(String msg)
    {
        this.msg = msg;
    }

    public T getData()
    {
        return data;
    }

    public void setData(T data)
    {
        this.data = data;
    }

    public static <T> Boolean isError(R<T> ret)
    {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(R<T> ret)
    {
        return ReturnCodeEnum.RC200.getCode().equals(ret.getCode());
    }
}
